package org.zfes.snowier.common.monitor.biz.service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zfes.snowier.common.monitor.biz.dao.MysqlMonitorMapper;
import org.zfes.snowier.common.monitor.biz.dto.MysqlMonitorDataDto;
import org.zfes.snowier.common.monitor.biz.model.MysqlMonitorEntity;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class MysqlMonitorDataService {
    @Autowired
    private MysqlMonitorMapper MysqlMapper;
    @Autowired
    private  MysqlAcutorService mysqlAcutorService;
    
    SimpleDateFormat format0 = new SimpleDateFormat("MM/dd HH:mm:ss");
    
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public List<MysqlMonitorEntity> findAllByInstanceKey(String instanceKey) {
    	Map<String, Object> paramMap=Maps.newHashMap();
    	paramMap.put("instanceKey", instanceKey);
    	 List<MysqlMonitorEntity> list=MysqlMapper.selectList(new QueryWrapper(paramMap));
    	 
    	 list.forEach(val->val.setDateStr(format0.format(val.getDate())));
        return list;
    }
    public void save( MysqlMonitorEntity entity) {
    	MysqlMapper.insert(entity);
    }

    @Async
    @Transactional
    public void save(String instanceKey,String mysqlMonitorInfo) {
    	MysqlMonitorDataDto dto = JSONObject.parseObject(mysqlMonitorInfo, MysqlMonitorDataDto.class);
    	
    	MysqlMonitorEntity entity=dto.toEntity();
    	entity.setInstanceKey(instanceKey);
    	entity.setGroupKey(StringUtils.substringBefore(instanceKey, "_"));
    	save(entity);
    	mysqlAcutorService.createInstance(instanceKey, entity);
    	 
    	 
    }
 
    
    @Async
    public void clearAll() {
    	MysqlMapper.deleteAll();
    }
}
